package mqtt

import (
	"com.smyx/cache"
	"com.smyx/util"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
)

func InitMqttConfig() {
	broker := fmt.Sprintf("tcp://%s:%d", cache.CfgStruct.MqttConfig.Ip, cache.CfgStruct.MqttConfig.Port)
	opts := mqtt.NewClientOptions().
		AddBroker(broker).
		SetUsername(cache.CfgStruct.MqttConfig.Username).
		SetPassword(cache.CfgStruct.MqttConfig.Password)
	cache.MClient = mqtt.NewClient(opts)

	if token := cache.MClient.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
}

// Subscribe 订阅主题
func Subscribe(topic string) {
	cache.MClient.Subscribe(topic, 0, func(client mqtt.Client, msg mqtt.Message) {
		util.SLogger.Infof("Topic: %s; Message: %s", msg.Topic(), msg.Payload())
	})
}

// Publish 发布主题
func Publish(topic, message string) {
	token := cache.MClient.Publish(topic, 0, false, message)
	token.Wait()
}
